<!--
 * @Description: 体重趋势页面
 * @Version: 1.0
 * @Author: Yuanjy
 * @Date: 2020-04-13 14:11:07
 * @LastEditors: Yuanjy
 * @LastEditTime: 2020-05-18 16:20:53
 -->
<template>
<el-dialog :visible.sync="weightShow" width="900px">
  <div class="user">
    <div class="user-content pd20-10">
      <div class="clearfix">
        <div class="fl week_type">
          <span :class="{active:rangeDay === 30}" @click="getWeightList(30)">最近一个月</span>
          <span :class="{active:rangeDay === 14}" @click="getWeightList(14)">最近两周</span>
          <span :class="{active:rangeDay === 7}" @click="getWeightList(7)">最近一周</span>
        </div>
        <div class="fr">
          <el-date-picker v-model="datepicker" type="daterange" size="small" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
          <el-button type="primary" size="small" @click="getWeightList()">搜索</el-button>
        </div>
      </div>
      <div style="width:850px; margin-top: 40px;">
        <p class="title">S轻体体重趋势<span class="w-tit">（本周期减重<span class="diff">{{ diff.current }}</span>Kg &nbsp;&nbsp;累计减重<span class="diff">{{ diff.total }}</span>Kg）</span></p>
        <!-- 体重趋势 echarts -->
        <div :id="id" style="width:850px; height:500px;" />
        <p class="weight-tip">PS: 如果用户未上传体重，趋势图中默认为前一天的数据</p>
      </div>
    </div>
  </div>
  <div class="user-box">
    <div class="tit">详细数据</div>
    <div class="user-content pd20-10">
      <div class="weight-data-box">
        <div class="custom-table" style="margin:0;">
          <el-table class="margin-non" :data="realWeightData" :header-row-class-name="'bg'" border max-height="400">
            <el-table-column label="日期" align="center">
              <template slot-scope="scope">
                {{ scope.row[0] }}
              </template>
            </el-table-column>
            <el-table-column label="体重(kg)" align="center">
              <template slot-scope="scope">
                {{ +scope.row[1] }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</el-dialog>
</template>

<script>
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/component/markLine'
import 'echarts/lib/component/markPoint'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/toolbox'
import loading from '@/views/components/loading1'
import { formatTime, getDayAgo } from '@/utils'

export default {
  components: {
    loading
  },
  data() {
    return {
      loadfull: false,
      weightShow: false,
      serviceId: 0,
      id: 'line',
      chart: null,
      time: [],
      weight: [],
      datepicker: [],
      type: '',
      diff: '',
      weightData: [],
      realWeightData: [],
      rangeDay: 30
    }
  },
  methods: {
    getWeightList(day, serviceId = 0) {
      if (+serviceId > 0) {
        this.serviceId = serviceId
      }
      this.rangeDay = day
      this.chart = echarts.init(document.getElementById(this.id))
      this.loadfull = true

      let start, end
      if (day) {
        start = getDayAgo(day)
        end = formatTime(new Date(), 'yyyy-MM-dd')
      } else {
        if (this.datepicker.length > 0) {
          start = this.datepicker[0]
          end = this.datepicker[1]
        } else {
          this.$notify({ title: '提示', message: '请选择时间', type: 'error', duration: 2500 })
          return 
        }
      }

      this.$api.order.dataTrend
        .getWeightData({
          params: { service_id: this.serviceId, start: start, end: end }
        })
        .then(res => {
          this.loadfull = false
          var response = res
          if (response.code === 200) {
            var list = response.data.list
            this.weightData = list
            this.realWeightData = res.data.real_list
            this.datepicker = [list[0][0], list[list.length - 1][0]]
            if (response.data.difference) {
              this.diff = response.data.difference
            }
            var time = []
            var weight = []
            list.forEach(item => {
              time.push(item[0])
              weight.push(item[1])
            })
            if (weight.findIndex((n) => n > 1) >= 0) {
              var i = 0
              for (i = 0; i < weight.length; i++) {
                if (weight[i] !== 0) {
                  break
                }
              }
              for (var j = i; j < weight.length; j++) {
                if (weight[j] === 0) {
                  weight[j] = weight[j - 1]
                }
              }
              for (var z = 0; z < weight.length; z++) {
                if (weight[z] === 0) {
                  weight[z] = null
                }
              }
            }
            this.setLine(time, weight)
          } else if (response.code === 200103) {
            this.$confirm('登录过期，请重新登录')
              .then(_ => {
                window.localStorage.clear()
                this.$router.push('/login')
              })
              .catch(_ => {})
          }
        }).catch(err => {
          console.log(err)
          this.loadfull = false
        })
    },
    setLine(time, weight) {
      var w = []
      for (var z = 0; z < weight.length; z++) {
        if (weight[z] !== null) {
          w.push(weight[z])
        }
      }
      // var maxWeight = Math.max.apply(Math, w)
      var mixWeight = Math.min.apply(Math, w)
      var mixW = Math.floor(mixWeight)
      this.chart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        toolbox: {
          show: true,
          feature: {
            // dataZoom: {
            //   yAxisIndex: 'none'
            // },
            // dataView: {readOnly: false},
            // magicType: {type: ['line']},
            // restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: time
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value} Kg'
          },
          min: mixW
        },
        series: [
          {
            name: '体重',
            type: 'line',
            data: weight,
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            }
          }
        ]
      })
    }
  }
}
</script>

<style scoped>
.margin-non {
  margin: 0;
}
</style>

<style scoped>
.user-content .week_type {
  display: inline-block;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  background: #fff;
  border: 1px solid #c4c4c4;
  color: #1f2d3d;
  margin: 0;
  padding: 0;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}
.user-content .week_type span {
  padding: 10px 15px;
  border-right: 1px solid #c4c4c4;
  display: inline-block;
}
.user-content .week_type span:hover, .user-content .week_type span.active{
  color: #20a0ff;
}
.user-content .week_type span:last-child {
  border-right: none;
}
.title {
  font-size: 18px;
  font-weight: bold;
  color: #000;
}
.title .w-tit {
  font-size: 16px;
  font-weight: normal;
}
.title .diff {
  color: #f00;
  display: inline-block;
  padding: 0 5px;
  font-weight: bold;
}
</style>
